import { setUser, removeUser, removeToken } from '@/global/storage'
import router from '@/router'

const state = {
  user: null
}

const mutations = {
  SET_USER(state, user) {
    if (user) {
      setUser(user)
    } else {
      removeUser()
      removeToken()
    }
    state.user = user
  }
}

const actions = {
  setUser({ commit }, user) {
    commit('SET_USER', user)
  },
  async logout({ commit }) {
    commit('SET_USER', null)
    await router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
